<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>交班管理 - 小型超市零售管理系统</title>
    <link rel="icon" type="image/x-icon" href="favicon.ico">
    <link rel="stylesheet" href="/css/style.css">
</head>
<body>
    <div class="header">
        <img src="../img/logo.png" class="logo" alt="logo">
        <span class="title">超市管理</span>
        <div class="nav">
            <span>前台POS</span>
            <span class="user">admin</span>
        </div>
    </div>
    <div class="sidebar">
        <ul>
            <li><a href="/page/index.html">收银台</a></li>
            <li><a href="/page/product.html">商品录入</a></li>
            <li class="active"><a href="/page/shift.html">交班管理</a></li>
            <li><a href="/page/admin.html">后台管理</a></li>
        </ul>
    </div>
    <div class="main">
        <div class="card">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h3>交班管理</h3>
                <button onclick="openAddShiftModal()" style="background: #43a047;">添加交班</button>
            </div>
            <table id="shiftTable">
                <thead>
                    <tr><th>交班时间</th><th>交班人</th><th>接班人</th><th>交班金额</th><th>总金额</th><th>备注</th><th>操作</th></tr>
                </thead>
                <tbody id="shiftTableBody">
                    <!-- 动态生成的行将在这里显示 -->
                </tbody>
            </table>
        </div>
    </div>

    <!-- 添加交班弹窗 -->
    <div id="addShiftModal" class="modal">
        <div class="modal-content">
            <h3 style="margin-top: 0; color: #2563eb;">添加交班记录</h3>
            <form id="addShiftForm">
                <div>
                    <label for="shiftDate">接班日期:</label>
                    <input type="datetime-local" id="shiftDate" required>
                </div>
                <div>
                    <label for="shiftPerson">接班人:</label>
                    <input type="text" id="shiftPerson" placeholder="请输入接班人姓名" required>
                </div>
                <div>
                    <label for="shiftAmount">接班金额:</label>
                    <input type="number" id="shiftAmount" placeholder="请输入金额" step="0.01" required>
                </div>
                <div>
                    <label for="shiftNote">备注:</label>
                    <input type="text" id="shiftNote" placeholder="请输入备注信息">
                </div>
                <div style="text-align: center; margin-top: 20px;">
                    <button type="submit" style="background: #43a047;">确认添加</button>
                    <button type="button" onclick="closeAddShiftModal()" style="background: #f44336;">取消</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 查看详情弹窗 -->
    <div id="detailModal" class="modal">
        <div class="modal-content">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h3 style="margin: 0; color: #2563eb;">交班详情</h3>
                <span class="close" onclick="closeDetailModal()" style="cursor: pointer; font-size: 24px; color: #999;">&times;</span>
            </div>
            <div id="detailContent" style="line-height: 1.8;">
                <!-- 详情内容将在这里动态生成 -->
            </div>
            <div style="text-align: center; margin-top: 20px;">
                <button onclick="closeDetailModal()" style="background: #2563eb;">关闭</button>
            </div>
        </div>
    </div>

    <!-- 成功提示弹窗 -->
    <div id="successModal" class="modal">
        <div class="modal-content" style="max-width: 400px;">
            <div style="text-align: center; padding: 20px;">
                <div style="font-size: 48px; color: #43a047; margin-bottom: 16px;">✓</div>
                <h3 style="margin: 0 0 16px 0; color: #43a047;">操作成功</h3>
                <p id="successMessage" style="margin: 0; color: #666; font-size: 16px;">交班记录添加成功！</p>
            </div>
            <div style="text-align: center; margin-top: 20px;">
                <button onclick="closeSuccessModal()" style="background: #43a047;">确定</button>
            </div>
        </div>
    </div>

    <script>
        // 交班数据管理
        let shiftData = [];
        let nextId = 1; // 下一个记录的ID
        
        // 从API获取入库记录数据
        async function loadShiftData() {
            try {
                console.log('请求获取入库记录数据...');
                const response = await fetch('/api/handover_getall', {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                    
                console.log('收到服务器响应:', response.status);
                const data = await response.json();
                console.log('响应数据:', data);
                    
                if (response.ok) {
                    shiftData = data; // 将API数据赋值给plansData
                    renderShiftTable();
                } else {
                    console.error('获取数据失败:', data.error);
                    renderShiftTable();
                }
            } catch (error) {
                console.error('获取数据错误:', error);
                renderShiftTable();
            }
        }
        // 渲染交班表格
        function renderShiftTable() {
            const tbody = document.getElementById('shiftTableBody');
            tbody.innerHTML = '';

            shiftData.forEach(shift => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${formatDateTime(shift.date)}</td>
                    <td>${shift.handover}</td>
                    <td>${shift.succession}</td>
                    <td>¥${shift.amount.toLocaleString('zh-CN', {minimumFractionDigits: 2})}</td>
                    <td>¥${shift.total_amount.toLocaleString('zh-CN', {minimumFractionDigits: 2})}</td>
                    <td>${shift.notes}</td>
                    <td><button onclick="viewShiftDetail(${shift.id})">查看详情</button></td>
                `;
                tbody.appendChild(row);
            });
        }

        // 添加新计划
        async function addNewPlan(shiftData = null) {
            let req;
            
            if (shiftData) {
                // 处理交班数据
                req = {
                    date: shiftData.date,
                    succession: shiftData.successionPerson,
                    amount: shiftData.amount,
                    notes: shiftData.note
                };
                console.log('添加交班记录数据...');
                console.log('请求数据:', req);
            }
            else{
                return;
            }
            
            try {
                const response = await fetch('/api/handover_create', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(req)
                });
                    
                console.log('收到服务器响应:', response.status);
                
                // 先读取响应文本
                const responseText = await response.text();
                console.log('服务器响应文本:', responseText);
                
                // 检查响应状态
                if (response.ok) {
                    try {
                        // 尝试解析JSON
                        const data = JSON.parse(responseText);
                        console.log('响应数据:', data);
                        loadShiftData();
                        document.getElementById('successMessage').innerText = '交班记录添加成功！';
                        document.getElementById('successModal').style.display = 'block';
                    } catch (jsonError) {
                        console.error('JSON解析错误:', jsonError);
                        alert('服务器响应格式错误，但交班记录可能已添加成功');
                        loadShiftData();
                    }
                } else {
                    // 处理HTTP错误状态
                    try {
                        const errorData = JSON.parse(responseText);
                        console.error('获取数据失败:', errorData.error);
                        alert('添加交班记录失败: ' + (errorData.error || '未知错误'));
                    } catch (jsonError) {
                        console.error('服务器错误响应:', responseText);
                        alert('添加交班记录失败: ' + responseText);
                    }
                }
            } catch (error) {
                console.error('网络请求错误:', error);
                alert('网络连接错误，请检查服务器是否正常运行');
            }
        }

        // 查看交班详情
        function viewShiftDetail(id) {
            const shift = shiftData.find(s => s.id === id);
            if (shift) {
                document.getElementById('detailContent').innerHTML = `
                    <table style="width: 100%; border-collapse: collapse; margin-top: 10px;">
                        <tr>
                            <td style="padding: 8px 12px; border-bottom: 1px solid #e5e7eb; font-weight: 600; width: 100px; color: #2563eb;">时间：</td>
                            <td style="padding: 8px 12px; border-bottom: 1px solid #e5e7eb;">${formatDateTime(shift.date)}</td>
                        </tr>
                        <tr>
                            <td style="padding: 8px 12px; border-bottom: 1px solid #e5e7eb; font-weight: 600; width: 100px; color: #2563eb;">交班人：</td>
                            <td style="padding: 8px 12px; border-bottom: 1px solid #e5e7eb;">${shift.handover}</td>
                        </tr>
                        <tr>
                            <td style="padding: 8px 12px; border-bottom: 1px solid #e5e7eb; font-weight: 600; width: 100px; color: #2563eb;">接班人：</td>
                            <td style="padding: 8px 12px; border-bottom: 1px solid #e5e7eb;">${shift.succession}</td>
                        </tr>
                        <tr>
                            <td style="padding: 8px 12px; border-bottom: 1px solid #e5e7eb; font-weight: 600; width: 100px; color: #2563eb;">交班金额：</td>
                            <td style="padding: 8px 12px; border-bottom: 1px solid #e5e7eb; font-weight: 500;">¥${shift.amount.toLocaleString('zh-CN', {minimumFractionDigits: 2})}</td>
                        </tr>
                        <tr>
                            <td style="padding: 8px 12px; border-bottom: 1px solid #e5e7eb; font-weight: 600; width: 100px; color: #2563eb;">总金额：</td>
                            <td style="padding: 8px 12px; border-bottom: 1px solid #e5e7eb; font-weight: 500;">¥${shift.total_amount.toLocaleString('zh-CN', {minimumFractionDigits: 2})}</td>
                        </tr>
                        <tr>
                            <td style="padding: 8px 12px; font-weight: 600; width: 100px; color: #2563eb;">备注：</td>
                            <td style="padding: 8px 12px;">${shift.notes}</td>
                        </tr>
                    </table>
                `;
                document.getElementById('detailModal').style.display = 'block';
            }
        }

        // 格式化日期时间
        function formatDateTime(dateTimeString) {
            if (!dateTimeString) return '';
            
            try {
                const date = new Date(dateTimeString);
                if (isNaN(date.getTime())) return dateTimeString; // 如果解析失败，返回原字符串
                
                // 返回ISO格式的日期字符串，但不包含时区信息
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');
                
                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            } catch (error) {
                console.error('日期格式化错误:', error);
                return dateTimeString; // 返回原字符串
            }
        }

        // 格式化日期时间为ISO格式（用于API请求）
        function formatDateTimeForAPI(dateTimeString) {
            if (!dateTimeString) return '';
            
            try {
                const date = new Date(dateTimeString);
                if (isNaN(date.getTime())) return dateTimeString;
                
                // 返回ISO格式的日期字符串
                return date.toISOString();
            } catch (error) {
                console.error('日期格式化错误:', error);
                return dateTimeString;
            }
        }

        function openAddShiftModal() {
            document.getElementById('addShiftModal').style.display = 'block';
            // 设置默认日期时间为当前时间
            const now = new Date();
            const dateTimeString = now.toISOString().slice(0, 16);
            document.getElementById('shiftDate').value = dateTimeString;
        }

        function closeAddShiftModal() {
            document.getElementById('addShiftModal').style.display = 'none';
            document.getElementById('addShiftForm').reset();
        }

        // 点击模态框外部关闭
        window.onclick = function(event) {
            var addModal = document.getElementById('addShiftModal');
            var detailModal = document.getElementById('detailModal');
            var successModal = document.getElementById('successModal');
            if (event.target == addModal) {
                closeAddShiftModal();
            }
            if (event.target == detailModal) {
                closeDetailModal();
            }
            if (event.target == successModal) {
                closeSuccessModal();
            }
        }

        // 表单提交处理
        document.getElementById('addShiftForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 获取表单数据
            var shiftDate = document.getElementById('shiftDate').value;
            var shiftPerson = document.getElementById('shiftPerson').value;
            var shiftAmount = parseFloat(document.getElementById('shiftAmount').value);
            var shiftNote = document.getElementById('shiftNote').value;
            
            // 数据验证
            if (!shiftDate || !shiftPerson || !shiftAmount || shiftAmount <= 0) {
                alert('请填写完整的有效信息！');
                return;
            }
            
            // 创建新的交班记录数据
            const newShift = {
                date: formatDateTimeForAPI(shiftDate), // 使用ISO格式
                successionPerson: shiftPerson,
                amount: shiftAmount,
                note: shiftNote || '无'
            };
            
            console.log('准备发送的交班数据:', newShift);
            
            // 调用addNewPlan函数发送数据到后端
            addNewPlan(newShift);
            
            // 关闭弹窗
            closeAddShiftModal();
        });

        // 页面加载时初始化表格
        document.addEventListener('DOMContentLoaded', function() {
            loadShiftData();
        });

        function closeDetailModal() {
            document.getElementById('detailModal').style.display = 'none';
        }

        function closeSuccessModal() {
            document.getElementById('successModal').style.display = 'none';
        }
    </script>
</body>
</html> 